package com.mty.kjtest.Rxjava;

import android.content.Context;
import rx.Subscriber;

/**
 * Created by 天宇 on 2017/6/30.
 */
public class ProgressSubscriber<T> extends Subscriber<T> implements ProgressCancelListener{

    private SubscriberOnNextListener<T> subscriberOnNextListener;
    private SubscriberonErrorListener subscriberonErrorListener;
    private Context context;

    private ProgressDialogHandler progressDialogHandler;



    public ProgressSubscriber(SubscriberOnNextListener<T> subscriberOnNextListener,SubscriberonErrorListener subscriberonErrorListener, Context context) {
        this.subscriberOnNextListener = subscriberOnNextListener;
        this.subscriberonErrorListener = subscriberonErrorListener;
        this.context = context;
        progressDialogHandler=new ProgressDialogHandler(context,true,this);

    }

    @Override
    public void onStart() {
        super.onStart();
        showProgressDialog();
    }

    private void  showProgressDialog(){
        if (progressDialogHandler!=null){
            progressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }


    private void dismissProgressDialog(){
        if (progressDialogHandler!=null){
            progressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            progressDialogHandler=null;
        }

    }

    @Override
    public void onCompleted() {
        dismissProgressDialog();
    }

    @Override
    public void onError(Throwable e) {
        subscriberonErrorListener.onError(e);
        dismissProgressDialog();
    }

    @Override
    public void onNext(T t) {
        subscriberOnNextListener.onNext(t);
    }

    @Override
    public void onCancelProgress() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }


    public interface SubscriberOnNextListener<T>{
        void onNext(T t);
    }

    public interface SubscriberonErrorListener{
        void onError(Throwable e);
    }




}


